<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form v-show="showSearch" ref="queryRef" :data="queryParams" layout="inline" reset-type="initial" label-width="calc(4em + 12px)">
        <t-form-item label="规则名称" name="ruleName">
          <t-input v-model="queryParams.ruleName" placeholder="请输入规则名称" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label-width="0px">
          <t-button theme="primary" @click="handleQuery">
            <template #icon> <search-icon /></template>
            搜索
          </t-button>
          <t-button theme="default" @click="resetQuery">
            <template #icon> <refresh-icon /></template>
            重置
          </t-button>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="ruleId"
        :data="profitRuleList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['system:profitRule:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>

              <t-button v-hasPermi="['system:profitRule:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>
        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <my-link v-hasPermi="['system:profitRule:query']" @click.stop="handleDetail(row)">
              <template #prefix-icon><browse-icon /></template>详情
            </my-link>
            <my-link v-hasPermi="['system:profitRule:edit']" @click.stop="handleUpdate(row)">
              <template #prefix-icon><edit-icon /></template>修改
            </my-link>
            <my-link v-hasPermi="['system:profitRule:remove']" size="small" @click.stop="handleDelete(row)">
              <template #prefix-icon><delete-icon /></template>删除
            </my-link>
          </t-space>
        </template>
      </t-table>
    </t-space>

    <!-- 添加或修改分佣规则对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="min(500px, 100%)"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="profitRuleRef.submit()"
    >
      <t-loading :loading="buttonLoading" size="small">
        <t-form
          ref="profitRuleRef"
          label-align="right"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          @submit="submitForm"
        >
          <t-form-item label="规则名称" name="ruleName">
            <t-input v-model="form.ruleName" placeholder="请输入规则名称" clearable />
          </t-form-item>
          <t-form-item label="规则描述" name="ruleDescription">
            <t-textarea v-model="form.ruleDescription" placeholder="请输入规则描述" />
          </t-form-item>
          <t-form-item label="规则类型" name="ruleType">
            <t-select v-model="form.ruleType" placeholder="请选择规则类型" clearable disabled>
              <t-option label="百分比" value="percentage" />
              <t-option label="固定金额" value="fixed" />
            </t-select>
          </t-form-item>
          <t-form-item label="一级分佣百分比" name="oneProfitPercentage">
            <t-input-number v-model="form.oneProfitPercentage" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="二级分佣百分比" name="twoProfitPercentage">
            <t-input-number v-model="form.twoProfitPercentage" placeholder="请输入" />
          </t-form-item>
          <t-form-item label="三级分佣百分比" name="threeProfitPercentage">
            <t-input-number v-model="form.threeProfitPercentage" placeholder="请输入" />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 分佣规则详情 -->
    <t-dialog
      v-model:visible="openView"
      header="分佣规则详情"
      placement="center"
      width="min(700px, 100%)"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">
        <t-descriptions-item label="规则id">{{ form.ruleId }}</t-descriptions-item>
        <t-descriptions-item label="规则名称">{{ form.ruleName }}</t-descriptions-item>
        <t-descriptions-item label="规则描述" :span="2">{{ form.ruleDescription }}</t-descriptions-item>
        <t-descriptions-item label="规则类型">{{ form.ruleType }}</t-descriptions-item>
        <t-descriptions-item label="一级分佣百分比">{{ form.oneProfitPercentage }}</t-descriptions-item>
        <t-descriptions-item label="二级分佣百分比">{{ form.twoProfitPercentage }}</t-descriptions-item>
        <t-descriptions-item label="三级分佣百分比">{{ form.threeProfitPercentage }}</t-descriptions-item>
        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>
        <t-descriptions-item label="更新时间">{{ parseTime(form.updateTime) }}</t-descriptions-item>
      </my-descriptions>
    </t-dialog>
  </t-card>
</template>
<script lang="ts" setup>
defineOptions({
  name: 'ProfitRule',
});
import {
  AddIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type { FormInstanceFunctions, FormRule, PageInfo, PrimaryTableCol, SubmitContext,  } from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';
import { ArrayOps } from '@/utils/array';

import type { SysProfitRuleForm, SysProfitRuleQuery, SysProfitRuleVo } from '@/api/system/model/profitRuleModel';
import { listProfitRule, getProfitRule, delProfitRule, addProfitRule, updateProfitRule } from '@/api/system/profitRule';

const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const profitRuleRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const profitRuleList = ref<SysProfitRuleVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);

// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({
  ruleName: [{ required: true, message: '规则名称不能为空' }, { max: 100, message: '规则名称不能超过100个字符' }],
  ruleType: [{ required: true, message: '规则类型不能为空' }, { max: 20, message: '规则类型不能超过20个字符' }],
  oneProfitPercentage: [{ required: true, message: '一级分佣百分比不能为空' }, { validator: (val) => val >= 0 && val <= 100, message: '一级分佣百分比必须在0-100之间' }],
  twoProfitPercentage: [{ required: true, message: '二级分佣百分比不能为空' }, { validator: (val) => val >= 0 && val <= 100, message: '二级分佣百分比必须在0-100之间' }],
  threeProfitPercentage: [{ required: true, message: '三级分佣百分比不能为空' }, { validator: (val) => val >= 0 && val <= 100, message: '三级分佣百分比必须在0-100之间' }],
});

// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center' },
  { title: `规则名称`, colKey: 'ruleName', align: 'center' },
  { title: `规则描述`, colKey: 'ruleDescription', align: 'center', ellipsis: true },
  { title: `规则类型`, colKey: 'ruleType', align: 'center', cell: (h, { row }) => row.ruleType === 'percentage' ? '百分比' : row.ruleType === 'fixed' ? '固定金额' : row.ruleType },
  { title: `一级分佣百分比`, colKey: 'oneProfitPercentage', align: 'center' },
  { title: `二级分佣百分比`, colKey: 'twoProfitPercentage', align: 'center' },
  { title: `三级分佣百分比`, colKey: 'threeProfitPercentage', align: 'center' },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 180 },
  { title: `更新时间`, colKey: 'updateTime', align: 'center', minWidth: 112, width: 180 },
  { title: `操作`, colKey: 'operation', align: 'center', width: 180 },
]);
// 提交表单对象
const form = ref<SysProfitRuleVo & SysProfitRuleForm>({});
// 查询对象
const queryParams = ref<SysProfitRuleQuery>({
  pageNum: 1,
  pageSize: 10,
  ruleName: undefined
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询分佣规则列表 */
function getList() {
  loading.value = true;
  listProfitRule(queryParams.value)
    .then((response) => {
      profitRuleList.value = response.rows;
      total.value = response.total;
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {
    ruleType: 'percentage'
  };
  proxy.resetForm('profitRuleRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加分佣规则';
}

/** 详情按钮操作 */
function handleDetail(row: SysProfitRuleVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const ruleId = row.ruleId;
  getProfitRule(ruleId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: SysProfitRuleVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改分佣规则';
  const ruleId = row?.ruleId || ids.value.at(0);
  getProfitRule(ruleId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    // 手动验证总和不超过100
    const one = Number(form.value.oneProfitPercentage) || 0;
    const two = Number(form.value.twoProfitPercentage) || 0;
    const three = Number(form.value.threeProfitPercentage) || 0;
    const total = one + two + three;
    
    if (total > 100) {
      proxy.$modal.msgError('一级、二级、三级分佣百分比总和不能超过100');
      return;
    }
    
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.ruleId) {
      updateProfitRule(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addProfitRule(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: SysProfitRuleVo) {
  const ruleIds = row?.ruleId || ids.value;
  proxy.$modal.confirm(`是否确认删除分佣规则编号为${ruleIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delProfitRule(ruleIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, ruleIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'system/profitRule/export',
    {
      ...queryParams.value,
    },
    `profitRule_${new Date().getTime()}.xlsx`,
  );
}

getList();
</script>
